/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.User;
import scheduler.formbean.AddBookmarkForm;
import scheduler.formbean.LoginForm;
import scheduler.model.BookmarkDao;
import scheduler.model.Model;
import scheduler.model.UserDao;


public class AddEntryAction extends Action {
	private static FormBeanFactory<AddBookmarkForm> formBeanFactory =
		FormBeanFactory.getInstance(AddBookmarkForm.class,"<>\"");
	
	private BookmarkDao entryDAO;

	private UserDao userDao;

    public AddEntryAction(Model model) {
		entryDAO = model.getBookmarkDao();
		userDao = model.getUserDao();
	}

    public String getName() { return "add-bookmark.do"; }

    public String perform(HttpServletRequest request) {
        try {
	        HttpSession session = request.getSession(true);
	        
			// Must be logged in for this one
	        User user = (User) session.getAttribute("user");
			if (user == null) {
				LoginForm form = new LoginForm();
				form.setRedirect("/add-bookmark.do");
		        request.setAttribute("form",form);
				return "login.jsp";
			}

			List<String> errors = new ArrayList<String>();
			AddBookmarkForm form = formBeanFactory.create(request);
			request.setAttribute("form",form);
	        request.setAttribute("errors",errors);
			
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (form.isEmpty()) {
	            return "add-bookmark.jsp";
	        }
	        
	        // Any validation errors?
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "add-bookmark.jsp";
	        }

	        entryDAO.create(user.getUserName(), form.getName(), form.getUrl(), form.getComment());
			request.setAttribute("registeredUsers", userDao.getAll());
			return "manage.do";
        } catch (DAOException e) {
        	e.printStackTrace();
        	request.setAttribute("dbError",e.getMessage());
        	return "db-error.jsp";
		}
    }
}
